package com.shigu.activity.service;

import com.opentae.data.mall.beans.FlashItemInfo;
import com.opentae.data.mall.beans.FlashSales;
import com.opentae.data.mall.beans.LimitGoods;
import com.opentae.data.mall.beans.MallItem;
import com.opentae.data.mall.examples.FlashSalesExample;
import com.opentae.data.mall.examples.MallItemExample;
import com.opentae.data.mall.interfaces.ActivityInfoMapper;
import com.opentae.data.mall.interfaces.FlashSalesMapper;
import com.opentae.data.mall.interfaces.MallItemMapper;
import com.shigu.PageResponse;
import com.shigu.account.api.VipManagerService;
import com.shigu.activity.api.ActivityGoodsService;
import com.shigu.activity.enums.KeywordType;
import com.shigu.activity.utils.TimeUtils;
import com.shigu.activity.vo.ActivityGoodsListVo;
import com.shigu.activity.vo.GoodsList;
import com.shigu.activity.vo.LimitGoodsListVo;
import com.shigu.appVersion.service.VersionService;
import com.shigu.exceptions.AdminException;
import com.shigu.exceptions.WapException;
import com.shigu.item.enums.ImgRule;
import com.shigu.util.MoneyUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Service(value = "activityGoodsServiceImpl")
public class ActivityGoodsServiceImpl implements ActivityGoodsService {

    @Resource(name = "vipManagerServiceImpl")
    VipManagerService vipManagerService;

    @Autowired
    MallItemMapper mallItemMapper;

    @Autowired
    ActivityInfoMapper activityInfoMapper;

    @Autowired
    FlashSalesMapper flashSalesMapper;

    @Resource(name = "versionService")
    VersionService versionService;


    @Override
    public ActivityGoodsListVo getActivityGoodsList(Long aId, Long userId, Integer page, Integer size,String version,
                                                    String os) throws WapException {
        String uri = versionService.versionUri(version,os);

        Double rate = vipManagerService.userRate(userId, uri);
        if(aId == 99){//限时抢购
            return getFlash(page,size,rate);
        }
        Integer type = activityInfoMapper.findActivityTitle(aId);
        if(type == null){
            throw new WapException("该活动已关闭");
        }
        if (type == KeywordType.RealProduct.getValue()) {//实时新品
            return getRealProduct(aId, page, size,rate);
        }
        if(type == KeywordType.HOTGOODS.getValue()){//热销好货
            return getHotGoods(aId,page,size,rate);
        }
        return null;
    }

    @Override
    public void setLimitGoods(Long goodsCode, Integer num, Integer weight) throws AdminException {
        if(goodsCode == null){
            throw new AdminException("请输入商品编号");
        }
        //查询商品是否存在
        if(mallItemMapper.selectByItemCode(String.valueOf(goodsCode)) == null){
            throw new AdminException("商品不存在");
        }
        //判断商品是否已经设置限时商品
        if(flashSalesMapper.findByItemCode(goodsCode) != null){
            throw new AdminException("该商品已经是限时商品");
        }
        if(num == null){
            throw new AdminException("请设置商品数量");
        }
        if(weight == null){
            throw new AdminException("请设置商品权重");
        }
        FlashSales flashSales = new FlashSales();
        flashSales.setItemCode(goodsCode);
        flashSales.setNumber(num);
        flashSales.setWeight(weight);
        flashSalesMapper.insertSelective(flashSales);
    }

    @Override
    public void modifyLimitGoods(Long goodsCode, Integer num, Integer weight) throws AdminException {
        if(goodsCode == null){
            throw new AdminException("请确认商品编号");
        }
        //查询商品是否存在
        if(mallItemMapper.selectByItemCode(String.valueOf(goodsCode)) == null){
            throw new AdminException("商品不存在");
        }
        if(num == null){
            throw new AdminException("请设置商品数量");
        }
        if(weight == null){
            throw new AdminException("请设置商品权重");
        }
        FlashSalesExample example = new FlashSalesExample();
        example.createCriteria().andItemCodeEqualTo(goodsCode);
        FlashSales flashSales = new FlashSales();
        flashSales.setNumber(num);
        flashSales.setWeight(weight);
        flashSalesMapper.updateByExampleSelective(flashSales,example);
    }

    @Override
    public void deleteLimitGoods(Long goodsCode) throws AdminException {
        if(goodsCode == null){
            throw new AdminException("商品编号不能为空");
        }
        FlashSalesExample example = new FlashSalesExample();
        example.createCriteria().andItemCodeEqualTo(goodsCode);
        flashSalesMapper.deleteByExample(example);
    }

    @Override
    public PageResponse<LimitGoodsListVo> getLimitGoodsList() {
        List<LimitGoods> limitGoods = mallItemMapper.getLimitGoods();
        PageResponse<LimitGoodsListVo> response = new PageResponse<>();

        response.setData(limitGoods.stream().map(o->{
            LimitGoodsListVo vo = new LimitGoodsListVo();
            vo.setGoodsCode(o.getGoodsCode());
            vo.setWeight(o.getWeight());
            String[] imgs = o.getImgSrc().split(",");
            vo.setImgSrc(imgs[0] + ImgRule.rule1.getText());
            vo.setTitle(o.getTitle());
            vo.setPrice(o.getPrice());
            vo.setCreatTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(o.getCreatTime()));
            vo.setNum(o.getNum());
            return vo;
        }).collect(Collectors.toList()));
        return response;
    }

    /**
     * @author 沐风
     * @Descirption 获取实时新品
     * @date 2019/8/30 5:29 PM
     */
    private ActivityGoodsListVo getRealProduct(Long aId, Integer page, Integer size,Double rate) {
        //查询用户分享的费率
        ActivityGoodsListVo vo = new ActivityGoodsListVo();
        int total = mallItemMapper.countByExample(new MallItemExample());
        vo.setHasNext(total > page * size);
        //实时新品显示50件
        if (page * size > 50) {
            size = 50 - (page - 1) * size;
            vo.setHasNext(false);
        }
        List<MallItem> mallItems = mallItemMapper.findByDate((page - 1) * size, size);
        vo.setData(mallItems.stream().map(o -> {
            GoodsList goods = new GoodsList();
            goods.setItemId(o.getItemId().toString());
            goods.setTitle(o.getTitle());
            String[] imgs = o.getImages().split(",");
            goods.setImgSrc(imgs[0] + ImgRule.rule1.getText());
            goods.setPrice(MoneyUtil.formatPriceMoney(o.getDiscount()));
            goods.setLiPrice(MoneyUtil.formatPriceMoney(o.getPrice()));
            goods.setCommission(MoneyUtil.formatPriceMoney(o.getDiscount() * rate));
            goods.setTipText(TimeUtils.getTime(o.getCreateTime()) + "上新");
            return goods;
        }).collect(Collectors.toList()));
        if (total > 50) {
            total = 50;
        }
        vo.setTotalNum(String.valueOf(total));
        vo.setBgImgSrc(activityInfoMapper.findBackGround(aId));
        vo.setCurTimeStamp(new Date().getTime());
        Calendar calendar = Calendar.getInstance();// 获取当前日期
        calendar.set(Calendar.HOUR_OF_DAY, 23);
        calendar.set(Calendar.MINUTE, 59);
        calendar.set(Calendar.SECOND, 59);
        vo.setEndTimeStamp(calendar.getTimeInMillis());
        return vo;
    }

    /**
     * @author 沐风
     * @Descirption 热销商品
     * @date 2019/8/30 8:22 PM
     */
    private ActivityGoodsListVo getHotGoods(Long aId, Integer page, Integer size,Double rate) {
        ActivityGoodsListVo vo = new ActivityGoodsListVo();
        int total = mallItemMapper.countByExample(new MallItemExample());
        vo.setHasNext(total > page * size);
        List<MallItem> hotGoods = mallItemMapper.findHotGoods((page - 1) * size, size);
        vo.setData(hotGoods.stream().map(o -> {
            GoodsList goods = new GoodsList();
            goods.setItemId(o.getItemId().toString());
            goods.setTitle(o.getTitle());
            String[] imgs = o.getImages().split(",");
            goods.setImgSrc(imgs[0] + ImgRule.rule1.getText());
            goods.setPrice(MoneyUtil.formatPriceMoney(o.getDiscount()));
            goods.setLiPrice(MoneyUtil.formatPriceMoney(o.getPrice()));
            goods.setCommission(MoneyUtil.formatPriceMoney(o.getDiscount() * rate));
            goods.setTipText("已售"+(o.getSales()+o.getFakeSales())+"件");
            return goods;
        }).collect(Collectors.toList()));
        vo.setTotalNum(String.valueOf(total));
        vo.setBgImgSrc(activityInfoMapper.findBackGround(aId));
        vo.setCurTimeStamp(new Date().getTime());
        Calendar calendar = Calendar.getInstance();// 获取当前日期
        calendar.set(Calendar.HOUR_OF_DAY, 23);
        calendar.set(Calendar.MINUTE, 59);
        calendar.set(Calendar.SECOND, 59);
        vo.setEndTimeStamp(calendar.getTimeInMillis());
        return vo;
    }

    /**
     * @author 沐风
     * @Descirption 热销商品
     * @date 2019/8/30 8:22 PM
     */
    private ActivityGoodsListVo getFlash(Integer page, Integer size,Double rate){
        ActivityGoodsListVo vo = new ActivityGoodsListVo();
        int total = flashSalesMapper.countByExample(new FlashSalesExample());
        vo.setHasNext(total > page * size);
        List<FlashItemInfo> hotGoods = mallItemMapper.findFlash((page - 1) * size, size);
        vo.setData(hotGoods.stream().map(o -> {
            GoodsList goods = new GoodsList();
            goods.setItemId(o.getItemId().toString());
            goods.setTitle(o.getTitle());
            String[] imgs = o.getImages().split(",");
            goods.setImgSrc(imgs[0] + ImgRule.rule1.getText());
            goods.setPrice(MoneyUtil.formatPriceMoney(o.getDiscount()));
            goods.setLiPrice(MoneyUtil.formatPriceMoney(o.getPrice()));
            goods.setCommission(MoneyUtil.formatPriceMoney(o.getDiscount() * rate));
            goods.setTipText("剩余"+o.getNumber()+"件");
            return goods;
        }).collect(Collectors.toList()));
        vo.setTotalNum(String.valueOf(total));
        vo.setBgImgSrc("");
        vo.setCurTimeStamp(new Date().getTime());
        Calendar calendar = Calendar.getInstance();// 获取当前日期
        calendar.set(Calendar.HOUR_OF_DAY, 23);
        calendar.set(Calendar.MINUTE, 59);
        calendar.set(Calendar.SECOND, 59);
        vo.setEndTimeStamp(calendar.getTimeInMillis());
        return vo;
    }
}
